new Vue({
    el: '#app',
    mixins: [Query],//组件配置文件，路径/utils/components.js
    data() {
        return {
            form: {//查询筛选
                value: '',
                value2: '-', // 状态：'-'全部、'0'待审核、'2'已通过、'3'拒绝
                PageNumber: 1, //页码
                RowAmount: 20,
                // Condition 两参：关键词,状态
                Condition: utf8ToBase64(`%%,%%`),
            },
            dialogInvoiceVisible: false,
            invoiceUploading: false,
            invoicePictureUrl: '',
            invoiceOrderRow: null,
        }
    },
    mounted() {
        /**
         * 组件配置文件中自动执行方法
         * 1.this.getColumn(); //查询表头数据
         * 2.this.getList(this.form); //查询表格数据
         * 3.this.getTreeData();//查询树
         */
    },
    methods: {
        isRejected(row) { // 仅拒绝状态显示“修改并重新提交”
            const s = (row && row.Row_Status) || '';
            return s !== '0' && s !== '1' && s !== '2';
        },
        handleCommand(command, row) {
            try {
                if (command === 'handleAdd') {
                    this.handleAdd(row);
                } else if (command === 'handleModifyResubmit') {
                    this.handleModifyResubmit(row);
                } else if (command === 'openInvoiceDialog') {
                    this.invoiceOrderRow = row;
                    this.invoicePictureUrl = '';
                    this.dialogInvoiceVisible = true;
                }
            } catch (error) {
                console.error(error);
                this.$message({ message: '系统错误，请联系开发者!', type: 'error' });
            }
        },
        async uploadInvoice(file) {
            try {
                const f = file && (file.raw || file);
                if (!f) return;
                const res = await generalApi.generalUploadStream(f);
                if (res && res.status === 'success') {
                    this.invoicePictureUrl = res.fileName;
                    this.$message.success('上传成功');
                } else {
                    this.$message.error('上传失败');
                }
            } catch (e) {
                console.error(e);
                this.$message.error('系统错误，请联系开发者!');
            }
        },
        async submitInvoice() {
            try {
                if (!this.invoiceOrderRow || !this.invoiceOrderRow.Acquisition_Order_SerialNumber) {
                    this.$message.error('未找到订单编号');
                    return;
                }
                if (!this.invoicePictureUrl) {
                    this.$message.warning('请先上传发票图片');
                    return;
                }
                this.invoiceUploading = true;
                const orderId = String(this.invoiceOrderRow.Acquisition_Order_SerialNumber || '');
                const now = getYMDHMSDate();
                const addRow = [{
                    Acquisition_Order_Invoice_SerialNumber: '',
                    Acquisition_Order_SerialNumber: orderId,
                    Acquisition_Order_Paystages_SerialNumber: '',
                    Picture_URL: String(this.invoicePictureUrl),
                    Enterprise_Info_SerialNumber: getCookie('enterprise') || '',
                    Creater_SerialNumber: getCookie('user') || '',
                    Create_Datetime: now,
                    Operation_ID: getCookie('user') || '',
                    Operation_Datetime: now,
                    Row_Status: '0'
                }];
                const lJSONObject_DataSet = { Add: { acquisition_order_invoice: addRow } };
                const Operation_Main = JSON.stringify(deepClone(lJSONObject_DataSet));
                lJSONObject_DataSet['Add']['base_operation_log'] = [{
                    Operation_Type: '0', Operation_Path: getRelativePath(),
                    Operation_Description: '上传采购订单发票', Operation_Main,
                    Operation_Interface: 'generalSaveByRequestBody', Operation_IP: getIpAddress()
                }];
                const res = await generalApi.generalSaveByRequestBody({ Data: lJSONObject_DataSet });
                this.invoiceUploading = false;
                if (res && res.Status === 'success') {
                    this.$message.success('提交成功');
                    this.dialogInvoiceVisible = false;
                    this.getList(this.form);
                } else {
                    this.$message.error('提交失败，请重试');
                }
            } catch (e) {
                console.error(e);
                this.invoiceUploading = false;
                this.$message.error('系统错误，请联系开发者!');
            }
        },
        handleSerach() { //筛选
            const val = this.form.value2;
            const status = (val === '-' || val === '' || val == null) ? '%%' : val;
            this.form.PageNumber = 1;
            this.form.Condition = utf8ToBase64(`%${this.form.value}%,${status}`);
            this.getList(this.form);
        },
        // 状态切换：更新 Condition 第二参数并刷新列表
        handleTabsClick() {
            const val = this.form.value2;
            const status = (val === '-' || val === '' || val == null) ? '%%' : val;
            this.form.PageNumber = 1;
            this.form.Condition = utf8ToBase64(`%${this.form.value}%,${status}`);
            this.getList(this.form);
        },
        handleAdd(row) { // 确认合同（卖方视角），跳转到卖家合同详情页
            try {
                const { primaryKey } = $('#table').data('options');
                const orderSerial = row.Acquisition_Order_SerialNumber || row[primaryKey] || '';
                if (!orderSerial) {
                    this.$message.error('未找到订单编号，无法跳转合同详情');
                    return;
                }
                const url = `../purchase_order/seller_contract_details.html?orderSerial=${encodeURIComponent(orderSerial)}`;
                window.location.href = url;
            } catch (error) {
                console.error(error);
                this.$message({ message: '系统错误，请联系开发者!', type: 'error' });
            }
        },
        handleShow(row) { // 查询详情：跳转到采购订单详情页
            try {
                const { primaryKey } = $('#table').data('options');
                const applyId = row.Acquisition_Order_SerialNumber || row[primaryKey] || '';
                if (!applyId) {
                    this.$message.error('未找到订单编号，无法跳转详情');
                    return;
                }
                const url = `./details.html?applyId=${encodeURIComponent(applyId)}&fromPage=acquisition_order`;
                window.location.href = url;
            } catch (error) {
                console.error(error);
                this.$message({ message: '系统错误，请联系开发者!', type: 'error' });
            }
        },
        handleModifyResubmit(row) { // 修改并重新提交：跳转到提交页的修改模式
            try {
                const { primaryKey } = $('#table').data('options');
                const acqId = row.Acquisition_Order_SerialNumber || row[primaryKey];
                if (!acqId) {
                    this.$message({ message: '未获取到报价订单编号', type: 'error' });
                    return;
                }
                window.location.href = `./add.html?action=Modify&nodeKey=${encodeURIComponent(acqId)}`;
            } catch (error) {
                console.error(error);
                this.$message({ message: '系统错误，请联系开发者!', type: 'error' });
            }
        },
        handleCancel(row) {//作废
            this.$confirm('警告！此操作将作废该数据, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                try {
                    const { tableName, primaryKey } = $('#table').data('options');
                    httpRequest({
                        url: '/generalBusiness/generalQueryByTableNameWithOriginal',
                        data: {
                            Data: tableName,
                            Condition: `${primaryKey}='${row[primaryKey]}'`
                        }
                    }).then(data => {
                        if (data.length == 1) {
                            data[0].Row_Status = '2';
                            let lJSONObject_Modify = new Object();
                            lJSONObject_Modify[tableName] = data;
                            //组合
                            let lJSONObject_DataSet = {
                                Modify: lJSONObject_Modify, Add: {}
                            };
                            let Operation_Main = JSON.stringify(deepClone(lJSONObject_DataSet));
                            lJSONObject_DataSet['Add']['base_operation_log'] = [{
                                Operation_Type: '0',
                                Operation_Path: getRelativePath(),
                                Operation_Description: '作废数据',
                                Operation_Main,
                                Operation_Interface: "generalSaveByRequestBody",
                                Operation_IP: getIpAddress()
                            }]
                            httpRequest({
                                contentType: 'JSON',
                                url: '/generalBusiness/generalSaveByRequestBody',
                                data: JSON.stringify({
                                    Data: lJSONObject_DataSet
                                })
                            }).then(res => {
                                if (res.Status == "success") {
                                    this.getList(this.form);
                                    this.$message.success("作废成功");
                                } else {
                                    this.$message.error("作废失败，请重试！");
                                }
                            }).catch(xhr => {
                                this.$message({
                                    message: '系统错误，请联系开发者!',
                                    type: 'error'
                                })
                            })
                        }
                    }).catch(xhr => {
                        this.$message({
                            message: '系统错误，请联系开发者!',
                            type: 'error'
                        })
                    })
                } catch (error) {
                    console.error(error);
                    this.$message({
                        message: '系统错误，请联系开发者!',
                        type: 'error'
                    })
                }
            }).catch(() => { });
        }
    }
})
